package com.mall.common.security.framework.handler;

import com.mall.common.core.enums.ErrorCodeEnum;
import com.mall.common.core.exception.ApiException;
import com.mall.common.core.model.response.ApiResponses;
import com.mall.common.core.utils.LogUtils;
import com.mall.common.security.utils.ResponseUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 *
 * @author Sam
 */
@Component
@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
//    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiResponses globalExceptionHandle(HttpServletRequest request, Exception e) {
        ApiResponses failure = ResponseUtils.failure(ErrorCodeEnum.INTERNAL_SERVER_ERROR.convert(), e);
        LogUtils.printExLog(request, failure, e);
        return failure;
    }

    @ResponseBody
    @ExceptionHandler(value = ApiException.class)
//    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiResponses globalExceptionHandle(HttpServletRequest request, ApiException e) {
        ApiResponses failure = ResponseUtils.failure(e.getErrorCode(), e);
        LogUtils.printExLog(request, failure, e);
        return failure;
    }

}